<?php
// public/employees.php
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/db.php';
require_login();


$con = mysqli_connect("localhost","root","","mydatabase");

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

  date_default_timezone_set("Asia/Manila"); 





// Session for flash messages
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Handle Add/Edit/Delete
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // --- Add Employee ---
    if (isset($_POST['add_employee'])) {
        $sql = "INSERT INTO employees (full_name, college_office, job_title, employment_type, contract_status, start_date, end_date)
                VALUES (?, ?, ?, ?, ?, ?, ?)";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([
            $_POST['full_name'],
            $_POST['college_office'],
            $_POST['job_title'],
            $_POST['employment_type'],
            $_POST['contract_status'],
            $_POST['start_date'],
            $_POST['end_date']
        ]);
        $emp_id = $pdo->lastInsertId();

     
$docTypes = [
    'medical_cert' => 'Medical Certificate',
    'nbi_clearance' => 'NBI/Police Clearance',
    'prc_license' => 'PRC License/Rating',
    'tor' => 'Transcript of Records',
    'psa_birth' => 'PSA Birth Certificate',
    'coe' => 'Certificate of Employment',
    'publications' => 'Publication Records'
];


    foreach ($docTypes as $field => $label) {
    // Check if at least one file was uploaded for this field
    if (!empty($_FILES[$field]['name'][0])) {

        // Loop through all uploaded files for this field
        for ($i = 0; $i < count($_FILES[$field]['name']); $i++) {

            $originalName = basename($_FILES[$field]['name'][$i]);
            $filename = time() . "_" . $i . "_" . $originalName;
            $target = __DIR__ . "/../uploads/" . $filename;

            if (move_uploaded_file($_FILES[$field]['tmp_name'][$i], $target)) {
                $stmt = $pdo->prepare("INSERT INTO documents (employee_id, doc_type, file_path) VALUES (?, ?, ?)");
                $stmt->execute([$emp_id, $label, 'uploads/' . $filename]);
            }
        }
    }
}

        $_SESSION['success'] = "Employee added successfully!";
        header("Location: employees.php");
        exit;
    }

    // --- Edit Employee ---
    if (isset($_POST['edit_employee'])) {
        $sql = "UPDATE employees 
                SET full_name=?, college_office=?, job_title=?, employment_type=?, contract_status=?, start_date=?, end_date=? 
                WHERE id=?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([
            $_POST['full_name'],
            $_POST['college_office'],
            $_POST['job_title'],
            $_POST['employment_type'],
            $_POST['contract_status'],
            $_POST['start_date'],
            $_POST['end_date'],
            $_POST['id']
        ]);

        // Handle new document uploads
        $docTypes = [
            'medical_cert' => 'Medical Certificate',
            'nbi_clearance' => 'NBI/Police Clearance',
            'prc_license' => 'PRC License/Rating',
            'tor' => 'Transcript of Records',
            'psa_birth' => 'PSA Birth Certificate',
            'coe' => 'Certificate of Employment',
            'publications' => 'Publication Records'
        ];

        foreach ($docTypes as $field => $label) {
            if (!empty($_FILES[$field]['name'])) {
                $filename = time() . "_" . basename($_FILES[$field]['name']);
                $target = __DIR__ . "/../uploads/" . $filename;
                if (move_uploaded_file($_FILES[$field]['tmp_name'], $target)) {
                    $stmt = $pdo->prepare("INSERT INTO documents (employee_id, doc_type, file_path) VALUES (?, ?, ?)");
                    $stmt->execute([$_POST['id'], $label, 'uploads/' . $filename]);
                }
            }
        }

        $_SESSION['success'] = "Employee updated successfully!";
        header("Location: employees.php");
        exit;
    }

    // --- Delete Employee ---
    if (isset($_POST['delete_employee'])) {
        $stmt = $pdo->prepare("DELETE FROM employees WHERE id=?");
        $stmt->execute([$_POST['id']]);

        $_SESSION['success'] = "Employee deleted successfully!";
        header("Location: employees.php");
        exit;
    }
}

$empQuery = $pdo->query("SELECT * FROM employees ORDER BY full_name ASC");
$employees = $empQuery->fetchAll(PDO::FETCH_ASSOC);

$title = "Employees | JO & COS RMS";
include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>

<!-- Page Header -->
<section class="content-header">
  <div class="container-fluid">
    <h1>Employees <small class="text-muted">Manage JO & COS Employees + Documents</small></h1>
  </div>
</section>

<!-- Flash Message -->
<?php if (!empty($_SESSION['success'])): ?>
<div class="alert alert-success alert-dismissible fade show mx-3" role="alert">
  <?= htmlspecialchars($_SESSION['success']) ?>
  <button type="button" class="close" data-dismiss="alert">&times;</button>
</div>
<?php unset($_SESSION['success']); endif; ?>

<!-- Page Content -->
<section class="content">
  <div class="card">
    <div class="card-header">
      <button class="btn btn-primary" data-toggle="modal" data-target="#addModal">
        <i class="fas fa-plus"></i> Add Employee
      </button>
    </div>
    <div class="card-body table-responsive">
    <table id="employeesTable" class="table table-bordered table-striped nowrap" style="width:100%">
    <thead>
        <tr>
            <th>Name</th>
            <th>College/Office</th>
            <th>Job Title</th>
            <th>Employment Type</th>
            <th>Status</th>
            <th>Start</th>
            <th>End</th>
            <th>Documents</th> 
            <th>Actions</th>
        </tr>
    </thead>
    <tbody>
        <?php foreach ($employees as $emp): ?>
            <tr>
                <td><?= htmlspecialchars($emp['full_name']) ?></td>
                <td><?= htmlspecialchars($emp['college_office']) ?></td>
                <td><?= htmlspecialchars($emp['job_title']) ?></td>
                <td><?= htmlspecialchars($emp['employment_type']) ?></td>
                <td><?= htmlspecialchars($emp['contract_status']) ?></td>
                <td><?= htmlspecialchars($emp['start_date']) ?></td>
                <td><?= htmlspecialchars($emp['end_date']) ?></td>

                <!-- ✅ DOCUMENTS COLUMN -->
                <td>
                    <?php
                    $stmt = $pdo->prepare("SELECT * FROM documents WHERE employee_id = ?");
                    $stmt->execute([$emp['id']]);
                    $docs = $stmt->fetchAll(PDO::FETCH_ASSOC);

                    if ($docs) {
                        echo "<ul class='mb-0 list-unstyled'>";
                        foreach ($docs as $doc) {
                            $filePath = htmlspecialchars($doc['file_path']);
                            $fileName = basename($filePath);
                            $docType = htmlspecialchars($doc['doc_type']);

                            echo "
                                <li class='mb-1'>
                                    <strong>{$docType}:</strong> 
                                    <a href='../{$filePath}' target='_blank' class='btn btn-sm btn-outline-primary'>
                                        <i class='fas fa-eye'></i> View
                                    </a>
                                    <a href='../{$filePath}' download='../{$fileName}' class='btn btn-sm btn-outline-success'>
                                        <i class='fas fa-download'></i> Download
                                    </a>
                                </li>
                            ";
                        }
                        echo "</ul>";
                    } else {
                        echo "<em>No documents</em>";
                    }
                    ?>
                </td>
            <td class="d-flex flex-wrap">
              <button class="btn btn-sm btn-info mr-1 mb-1" data-toggle="modal" data-target="#editModal<?= $emp['id'] ?>"><i class="fas fa-edit"></i></button>
              <form method="post" style="display:inline;">
                <input type="hidden" name="id" value="<?= $emp['id'] ?>">
                <button type="submit" name="delete_employee" class="btn btn-sm btn-danger mb-1" onclick="return confirm('Delete this employee?');"><i class="fas fa-trash"></i></button>
              </form>
            </td>
          </tr>

          <!-- Edit Modal -->
          <div class="modal fade" id="editModal<?= $emp['id'] ?>" tabindex="-1">
            <div class="modal-dialog modal-lg">
              <div class="modal-content">
                <form method="post" enctype="multipart/form-data">
                  <div class="modal-header">
                    <h5 class="modal-title">Edit Employee</h5>
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                  </div>
                  <div class="modal-body">
                    <input type="hidden" name="id" value="<?= $emp['id'] ?>">
                    <div class="form-row">
                      <div class="form-group col-md-6">
                        <label>Full Name</label>
                        <input type="text" name="full_name" class="form-control" value="<?= htmlspecialchars($emp['full_name']) ?>" required>
                      </div>
                      <div class="form-group col-md-6">
                        <label>College/Office</label>
                        <select name="college_office" class="form-control" value="<?= htmlspecialchars($emp['college_office']) ?>">
						<option value="College of Arts and Sciences" >College of Arts and Sciences</option>
						
						</select>
						
						
					
                      </div>
                    </div>
                    <div class="form-row">
                      <div class="form-group col-md-6">
                        <label>Job Title</label>
                        <input type="text" name="job_title" class="form-control" value="<?= htmlspecialchars($emp['job_title']) ?>" required>
                      </div>
                      <div class="form-group col-md-6">
                        <label>Employment Type</label>
                        <select name="employment_type" class="form-control" required>
                          <option value="JO" <?= $emp['employment_type']=='JO'?'selected':'' ?>>JO</option>
                          <option value="COS" <?= $emp['employment_type']=='COS'?'selected':'' ?>>COS</option>
                        </select>
                      </div>
                    </div>
                    <div class="form-row">
                      <div class="form-group col-md-6">
                        <label>Contract Status</label>
                        <select name="contract_status" class="form-control" required>
                          <option value="Active" <?= $emp['contract_status']=='Active'?'selected':'' ?>>Active</option>
                          <option value="Expired" <?= $emp['contract_status']=='Expired'?'selected':'' ?>>Expired</option>
                          <option value="Resigned" <?= $emp['contract_status']=='Resigned'?'selected':'' ?>>Resigned</option>
                        </select>
                      </div>
                      <div class="form-group col-md-3">
                        <label>Start Date</label>
                        <input type="date" name="start_date" class="form-control" value="<?= $emp['start_date'] ?>" required>
                      </div>
                      <div class="form-group col-md-3">
                        <label>End Date</label>
                        <input type="date" name="end_date" class="form-control" value="<?= $emp['end_date'] ?>">
                      </div>
                    </div>

                    <h6>Upload Documents (Optional)</h6>
                    <div class="form-row">
                      <div class="form-group col-md-6"><label>Medical Certificates</label><input type="file" name="medical_cert" class="form-control-file"></div>
                      <div class="form-group col-md-6"><label>NBI/Police Clearance</label><input type="file" name="nbi_clearance" class="form-control-file"></div>
                      <div class="form-group col-md-6"><label>PRC License/Rating</label><input type="file" name="prc_license" class="form-control-file"></div>
                      <div class="form-group col-md-6"><label>Transcript of Records</label><input type="file" name="tor" class="form-control-file"></div>
                      <div class="form-group col-md-6"><label>PSA Birth Certificate</label><input type="file" name="psa_birth" class="form-control-file"></div>
                      <div class="form-group col-md-6"><label>Certificate of Employment</label><input type="file" name="coe" class="form-control-file"></div>
                      <div class="form-group col-md-12"><label>Publication Records</label><input type="file" name="publications" class="form-control-file"></div>
                    </div>
                  </div>
                  <div class="modal-footer">
                    <button type="submit" name="edit_employee" class="btn btn-success">Update</button>
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                  </div>
                </form>
              </div>
            </div>
          </div>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
</section>

<!-- Add Employee Modal -->
<div class="modal fade" id="addModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <form method="post" enctype="multipart/form-data">
        <div class="modal-header">
          <h5 class="modal-title">Add Employee</h5>
          <button type="button" class="close" data-dismiss="modal">&times;</button>
        </div>
        <div class="modal-body">
          <div class="form-row">
            <div class="form-group col-md-6"><label>Full Name</label><input type="text" name="full_name" class="form-control" required></div>
          <div class="form-group col-md-6">  <label>Office/College</label><select name="college_office" class="form-control" required>
						
						<option value="College of Arts and Sciences" >College of Arts and Sciences</option>
						<option value="College of Industrial Technology" >College of Industrial Technology</option>
						<option value="College of Education" >College of Education</option>
						<option value="College of Agriculture" >College of Agriculture</option>
						<option value="College of Engeneering" >College of Engeneering</option>
						<option value="Office of the Vice President Academic Affaires" >Office of the Vice President Academic Affaires</option>
						<option value="Office of the President" >Office of the President</option>
						<option value="Office of the Registrar" >Office of the Registrar</option>
						<option value="Human Resource Management Office" >Human Resource Management Office</option>
						<?php
						$query2=mysqli_query($con,"select * from department")or die(mysqli_error());
		while($rowc=mysqli_fetch_array($query2)){
	
						?>
		<option value="<?php echo $rowc['college_office']; ?>"><?php echo $rowc['college_office']; }?></option>
						
						
						</select></div>
          </div>
          <div class="form-row">
            <div class="form-group col-md-6">  <label>Job Title</label><select name="job_title" class="form-control" required>
						
						<option value="Instructor 1" >Instructor</option>
						
						
						<?php
						$query1=mysqli_query($con,"select * from job")or die(mysqli_error());
		while($row1=mysqli_fetch_array($query1)){
	
						?>
		<option value="<?php echo $row1['jobname']; ?>"><?php echo $row1['jobname']; }?></option>
						
						
						</select></div>
			
			
			
			
            <div class="form-group col-md-6">
              <label>Employment Type</label>
              <select name="employment_type" class="form-control" required>
                <option value="JO">JO</option>
                <option value="COS">COS</option>
              </select>
            </div>
          </div>
          <div class="form-row">
            <div class="form-group col-md-6">
              <label>Contract Status</label>
              <select name="contract_status" class="form-control" required>
                <option value="Active">Active</option>
                <option value="Expired">Expired</option>
                <option value="Terminated">Resigned</option>
              </select>
            </div>
            <div class="form-group col-md-3"><label>Start Date</label><input type="date" name="start_date" class="form-control" required></div>
            <div class="form-group col-md-3"><label>End Date</label><input type="date" name="end_date" class="form-control"></div>
          </div>

          <h6>Upload Documents (Optional)</h6>
          <div class="form-row">
            <div class="form-group col-md-6"><label>Medical Certificates</label><input type="file" name="medical_cert[]" multiple class="form-control-file"></div>
            <div class="form-group col-md-6"><label>NBI/Police Clearance</label><input type="file" name="nbi_clearance[]" multiple class="form-control-file"></div>
            <div class="form-group col-md-6"><label>PRC License/Rating</label><input type="file" name="prc_license[]" multiple class="form-control-file"></div>
            <div class="form-group col-md-6"><label>Transcript of Records</label><input type="file" name="tor[]" multiple class="form-control-file"></div>
            <div class="form-group col-md-6"><label>PSA Birth Certificate</label><input type="file" name="psa_birth[]" multiple class="form-control-file"></div>
            <div class="form-group col-md-6"><label>Certificate of Employment</label><input type="file" name="coe[]" multiple class="form-control-file"></div>
            <div class="form-group col-md-12"><label>Publication Records</label><input type="file" name="publications[]" multiple class="form-control-file"></div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="submit" name="add_employee" class="btn btn-primary">Save</button>
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
        </div>
      </form>
    </div>
  </div>
</div>

<?php include __DIR__ . '/../includes/footer.php'; ?>

<!-- DataTables -->
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap4.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.5.0/js/dataTables.responsive.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap4.min.css"/>
<link rel="stylesheet" href="https://cdn.datatables.net/responsive/2.5.0/css/responsive.bootstrap4.min.css"/>

<script>
$(function () {
  $('#employeesTable').DataTable({
    responsive: true,
    autoWidth: false
  });
});
</script>
